package tmall.framework.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tmall.framework.response.ResponseResult;

import java.sql.SQLException;


@Slf4j
@RestControllerAdvice
public class GlobleExceptionHandler {
    public static final String LEFT_BRACKET = "{";
    public static final String RIGHT_BRACKET = "}";

    @ExceptionHandler(TException.class)
    public ResponseResult handlerTException(TException e) {
        log.error("exception----->",e);
        String msg = e.getMsg();
        if (StringUtils.isEmpty(msg)) {
            return ResponseResult.failed("", e.getCode());
        }
        Object[] objs = e.getArgs();
        if (objs == null || objs.length == 0) {
            return ResponseResult.failed(msg, e.getCode());
        }
        for (int ind = 0; ind < objs.length; ind++) {
            String matcher = LEFT_BRACKET + ind + RIGHT_BRACKET;
            msg = msg.replaceFirst(matcher, objs[0].toString());
        }
        return ResponseResult.failed(msg, e.getCode());
    }

    @ExceptionHandler(SQLException.class)
    public ResponseResult handlerSQLException(SQLException e) {
        ErrorEnum errorEnum  = FrameworkExceptionDict.SQL_EXCEPTION;
        String sql = e.getSQLState();
        if(StringUtils.isEmpty(sql)){
            sql = e.getMessage();
        }
        if(StringUtils.isEmpty(sql)){
            sql = e.getStackTrace().toString();
        }
        String matcher = LEFT_BRACKET+"0"+ RIGHT_BRACKET;
        String msg = errorEnum.getMsg().replace(matcher,sql);
        log.error("exception----->",e);
        return ResponseResult.failed(msg, errorEnum.getCode());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult handlerException(Exception e) {
        log.error("exception----->",e);
        ErrorEnum errorEnum  = FrameworkExceptionDict.SERVER_EXCEPTION;
        return ResponseResult.failed(errorEnum.getMsg(), errorEnum.getCode());
    }
}
